package xyz.labmem.main.modular.common.service

import com.alibaba.excel.context.AnalysisContext
import com.alibaba.excel.read.listener.ReadListener
import xyz.labmem.base.core.consts.log
import xyz.labmem.base.core.tool.allFieldIsNULL
import xyz.labmem.main.modular.common.mapper.AppBaseMapper


/**
 * @Author lty
 * @Date 2021/12/23 9:20
 */
class AppTableExcelListener<T>(private val mapper: AppBaseMapper<T>) : ReadListener<T> {

    private val log = this.log()

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private val BATCH_COUNT = 100

    /**
     * 缓存的数据
     */
    private var cachedDataList = ArrayList<T>(BATCH_COUNT)

    override fun invoke(data: T, p1: AnalysisContext) {
        if (!(data as Any).allFieldIsNULL()) {
            cachedDataList.add(data)
            // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (cachedDataList.size >= BATCH_COUNT) {
                saveData()
                // 存储完成清理 list
                cachedDataList.clear()
            }
        }
    }

    override fun doAfterAllAnalysed(p0: AnalysisContext?) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData()
        log.info("所有数据解析完成！")
    }

    private fun saveData() {
        if (cachedDataList.size > 0) {
            log.info("${cachedDataList.size}条数据，开始存储数据库！")
            mapper.insertBatchSomeColumn(cachedDataList)
            log.info("存储数据库成功！")
        } else
            log.warn("未获取到数据！")
    }

}